package com.ihome.android.market2.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.ihome.android.EAApp;
import com.ihome.android.EAFragment;
import com.ihome.android.academy.AlbumActivity;
import com.ihome.android.academy.AlbumAppActivity;
import com.ihome.android.academy.AppMgrActivity;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.academy.RankingActivity;
import com.ihome.android.academy.SectionAppActivity;
import com.ihome.android.academy.WebViewActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.PosterType;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetSectionContentTask;
import com.ihome.android.market2.asynctask.GetViewAppDetailTask;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.view.MyScaleItem;
import com.ihome.android.util.ImageHelper;
import com.ihome.android.util.Util;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

public class RecommAppFragment extends EAFragment {
	private String						TAG				= RecommAppFragment.class.getSimpleName();
	private View						fragview;
	@EAInjectView(id = R.id.rl_main)
	private RelativeLayout				rl_main;

	@EAInjectView(id = R.id.iv_inverted_view)
	private ImageView					iv_inverted_view;
	@EAInjectView(id = R.id.ll_data_tip)
	private RelativeLayout ll_data_tip;
	private List<TemplateContentInfo>	mPosterList;
	private int							sapce			= 5;

	private int							focusedPos		= 0;
	private List<MyScaleItem>			mScaleItemList;

	private int							preItemWidth	= 0;
	private int							preItemHeight	= 0;

	private int							totalMarginTop	= 0;
	private int							totalMarginLeft	= 0;

	private int							mPreRow			= 0;
	private int							mPreColumn		= 0;

	private Bitmap						mShadowBitmap	= null;

	/** 更新倒影 */
	private final int					UPDATE_SHADOW	= 0x1000;
	/** 加载图片 */
	private ImageLoader					imageLoader;
	/** 当前Section ID */
	private int							mSectionID		= -1;

	private Handler						mHandler		= new Handler() {
															public void handleMessage(android.os.Message msg) {
																switch (msg.what) {
																case UPDATE_SHADOW:
																	updateShadow(rl_main, iv_inverted_view);
																	break;

																default:
																	break;
																}

															};
														};

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mSectionID = getArguments().getInt(HttpKeys.KEY_SECTIONID, -1);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageLoader = ImageLoaderFactory.create(getActivity());
//		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.default_recomm_item);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d(TAG, " --> onCreateView() position = " + focusedPos);
		fragview = (HorizontalScrollView) inflater.inflate(R.layout.frag_recomm_app, container, false);
		
		int sectionId = getArguments().getInt(HttpKeys.KEY_SECTIONID);
		mPosterList  = EAApp.getApp().getRecommListByID(sectionId);
		if (mPosterList == null || mPosterList.size() == 0) {
			new GetSectionContentTask(getActivity(), this).execute(getArguments());
		}
			
		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		if(totalMarginLeft == 0 && totalMarginTop ==0 && mPosterList != null){
			initView();
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() position = " + focusedPos);
		//setItemOnFocuse();
	}

	public void setData(List<TemplateContentInfo> posterList) {
		if(posterList!=null && posterList.size()>0){
			ll_data_tip.setVisibility(View.GONE);
		}else{
			RelativeLayout.LayoutParams lp1 = (android.widget.RelativeLayout.LayoutParams) ll_data_tip.getLayoutParams();
			lp1.width = Util.getWindowWidth(getActivity());
			ll_data_tip.setLayoutParams(lp1);
			ll_data_tip.setVisibility(View.VISIBLE);
		}
		mPosterList = posterList;
		initView();
		LogUtil.d(TAG, " --> setData() fsdfsdfs = " + posterList.size());

		
	}

	private void initView() {
		LogUtil.d(TAG, " --> initView() position = " + focusedPos);
		rl_main.removeAllViews();
		if (mScaleItemList == null)
			mScaleItemList = new ArrayList<MyScaleItem>();

		int index = 0;
		for (TemplateContentInfo info : mPosterList) {
			info.setPosition(index);
			addMyScaleView(info);
			index++;
		}

		rl_main.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		int w = rl_main.getMeasuredWidth() + 5 * sapce;
		int h = rl_main.getMeasuredHeight() + 5 * sapce;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h);
		//params.topMargin = sapce ;
		rl_main.setLayoutParams(params);

	}

	private void addMyScaleView(final TemplateContentInfo info) {
		
		LogUtil.d(TAG, " --> addMyScaleView() info.getPosterUrl() = " + info.getPosterUrl());

		int width = Util.getWindowWidth(getActivity());

		int widthItemSmall = info.getmWidth() * width / 1920;
		int heightItemSmall = info.getmHeight() * width / 1920;

		int widthItem = widthItemSmall;
		int heightItem = heightItemSmall;
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.default_recomm_item);
		MyScaleItem scaleItem = new MyScaleItem(getActivity(), this, imageLoader);
		scaleItem.setImgSrc(R.drawable.default_recomm_item);
		scaleItem.setTag(info);
		scaleItem.setImageUrl(info.getPosterUrl());
		scaleItem.setClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				postClick(info);
			}
		});
		if (mScaleItemList.size() < mPosterList.size()) {
			mScaleItemList.add(scaleItem);
		}
		rl_main.addView(scaleItem.getView());

		for (TemplateContentInfo preinfo : mPosterList) {
			if (info.getmRow() == preinfo.getmRow() && info.getmCol() == (preinfo.getmCol() + 1)) {
				preItemWidth = preinfo.getmWidth() * width / 1920;
				LogUtil.w(TAG, " --> addMyScaleView() preItemWidth = " + preItemWidth);
				break;
			}
		}

		/**
		 * 首先确定所在列，初始化行数据
		 */
		if (info.getmCol() > mPreColumn) {
			totalMarginLeft += (sapce + preItemWidth);
			totalMarginTop = 0;
			mPreRow = 1;
		}
		mPreColumn = info.getmCol();

		/**
		 * 根据行数，累加 marginTop
		 */
		if (info.getmRow() > mPreRow) {
			totalMarginTop += (sapce + preItemHeight);
		}
		mPreRow = info.getmRow();
		preItemHeight = heightItem;
		if (info.getmCol() - 1 > mPreColumn) {
			mPreColumn += info.getmColSpan();
			totalMarginLeft += sapce + widthItem;
		}

		RelativeLayout.LayoutParams tvParams1 = new RelativeLayout.LayoutParams(widthItem, heightItem);
		scaleItem.setTextViewLayout(tvParams1);
		RelativeLayout.LayoutParams rlParams1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		//第一行item 的 Extra
		int topExtra = 18;
		rlParams1.topMargin = totalMarginTop + topExtra;
		
		//第一列item 的 Extra
		int leftExtra = 18;
		rlParams1.leftMargin = totalMarginLeft + leftExtra;
		scaleItem.setLayoutParams(rlParams1);
	}

	private void updateShadow(View view, ImageView imageView) {
		LogUtil.d(TAG, " --> updateShadow() imageView = " + imageView);

		if (view.getWidth() < 1 || view.getHeight() < 1) {
			return;
		}

		if (mShadowBitmap != null  && !mShadowBitmap.isRecycled()) {
			mShadowBitmap.recycle();
			mShadowBitmap = null;
		}

		mShadowBitmap = ImageHelper.createReflectedImage(view, Util.convertDIP2PX(getActivity(), 100), -65);
		imageView.setImageBitmap(mShadowBitmap);

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
		params.topMargin = rl_main.getMeasuredHeight() - 85;
		params.height = Util.convertDIP2PX(getActivity(), 100);
		params.width = view.getWidth();
		imageView.setLayoutParams(params);
	}

	private void postClick(TemplateContentInfo info) {
		LogUtil.v(TAG, " --> postClick() info = " + new Gson().toJson(info));

		switch (info.getType()) {
		case PosterType.POSTER_TYPE_APP:
			try {
				Bundle b = new Bundle();
				b.putInt(HttpKeys.KEY_APPID, info.getContentId());
				b.putString(HttpKeys.KEY_PATHID, "");
				new GetViewAppDetailTask(RecommAppFragment.this.getActivity(),
						RecommAppFragment.this,info.getContentId()).execute(b);
				/** 用户行为统计 */
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), "", "" + info.getContentId(), "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_RECOMMAND_APP, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			break;
		case PosterType.POSTER_TYPE_CATEGORY:

			if (info.getContentCode().equals(PosterType.SECTION_TYPE_APPMGR)) {
				getActivity().startActivity(new Intent(getActivity(), AppMgrActivity.class));
				/** 用户行为统计 “应用管理”点击行为*/
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), "", "" , "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_APPMGR, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			}
			if (info.getContentCode().equals(PosterType.SECTION_TYPE_PUREAPP)) {
				Intent intent = new Intent(getActivity(), AlbumAppActivity.class);
				intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
				intent.putExtra(AlbumAppActivity.APP_COLLECTION_NAME, info.getName());
				getActivity().startActivity(intent);
				
				/** 用户行为统计 专辑点击行为*/
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), ""+ info.getContentId(), "" , "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_RECOMMAND_ALBUM, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			}
			if (info.getContentCode().equals(PosterType.SECTION_TYPE_SUB)) {
				Intent intent = new Intent(getActivity(), SectionAppActivity.class);
				intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
				getActivity().startActivity(intent);
				
				/** 用户行为统计 专题点击行为*/
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), ""+ info.getContentId(), "" , "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_RECOMMAND_TOPIC, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			}
			if (info.getContentCode().equals(PosterType.SECTION_TYPE_RANKLIST)) {
				Intent intent = new Intent(getActivity(), RankingActivity.class);
				intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
				getActivity().startActivity(intent);
				
				/** 用户行为统计 “排行榜”点击行为*/
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), ""+ info.getContentId(), "" , "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_RECOMMAND_RANK, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			}
			if (info.getContentCode().equals(PosterType.SECTION_TYPE_ALBUM)) {
				Intent intent = new Intent(getActivity(), AlbumActivity.class);
				intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
				getActivity().startActivity(intent);
				
				/** 用户行为统计 专辑点击行为*/
				int size = EAApp.getApp().mCategoryList.size();
				for (int i = 0; i < size; i++) {
					if (mSectionID == EAApp.getApp().mCategoryList.get(i).getContentId()) {
						String[] msg = { i + "_" + info.getmRow() + "_" + info.getmCol(), ""+ info.getContentId(), "" , "" + mSectionID, "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_RECOMMAND_ALBUM, NotifyType.TYPE_NORMAL, "", msg);
						break;
					}
				}
			}
			break;
		case PosterType.POSTER_TYPE_URLLINK:
			if (info.getContentId() > 0) {
				Intent intent = new Intent(getActivity(), WebViewActivity.class);
				intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
				getActivity().startActivity(intent);
			}
			else {
				LogUtil.e(TAG, "mPosters[i].getContent() is NULL");
			}

			break;
		default:
			break;
		}
	}

	public void setFocusedPosition(int pos) {
		LogUtil.d(TAG, "--> setFocusedPosition() position = " + pos);
		 focusedPos = pos;
	}

	public boolean isAtTop(){
		if(focusedPos < mPosterList.size()){
			TemplateContentInfo info = mPosterList.get(focusedPos);
			if(info.getmRow() == 1){
				return true;
			}
		}
		return false;
	}

	public void setItemOnFocuse() {
		if (mScaleItemList != null && mScaleItemList.size() > focusedPos) {
			LogUtil.d(TAG, " --> setItemOnFocuse() position = " + focusedPos);
			mScaleItemList.get(focusedPos).getView().requestFocus();
		}
	}

	public void toDetailPage(int appId){
		Intent intent = new Intent();
		intent.putExtra(HttpKeys.KEY_APPID, appId);
		intent.setClass(getActivity(), DetailActivity.class);
		getActivity().startActivity(intent);
	}
}
